<template  >
  <van-nav-bar :title="t('home.无头件列表')" left-arrow @click-left="onClickLeft" />

  <van-tabs v-model:active="active" >
    <!-- <template  >  -->
    <van-pull-refresh   v-model="loadingRefresh" @refresh="onRefresh">
      <!-- <van-list
          :loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          :offset="tabs.offset[item.key]"
          @load="listOnLoad"
        > -->
      <van-tab v-for="item in tabs.tabName" :key="item.key" :title="item.title">
        <template v-if="item.key == 'PHOTO'">
          <div>
            <van-field
              id="scan_order"
              v-model="scan"
              :placeholder="t('printPage.请扫描条码')"
              @keydown.enter="handleScan"
            />
            <Tip :state="tipState" />

            <template v-if="'id' in unknowOrder">
              <van-field :label="t('uknownList.单号')">
                <template #input>
                  {{ unknowOrder['packageNumber'] }}
                  </template>
              </van-field>
              
              <van-field :label="t('uknownList.库位')">
                <template #input>
                  {{ unknowOrder['storageBlock'] }}
                  </template>
              </van-field>
              
              <van-field :label="t('uknownList.图片')">
                <template #input>
                  <van-uploader v-model="fileList" :after-read="afterRead" />
                </template>
              </van-field>
              <van-field>
                <template #input>
                  <van-button
                    size="small"
                    class="w-full p-8"
                    type="success"
                    @click="handleHeadlessFormSubmit"
                    >{{ t("confirm") }}</van-button
                  >
                </template>
              </van-field>
            </template>
          </div>
        </template>

        <template v-if="item.key == 'TOHANDLE'">
          <van-cell>
            <template #title>
              <van-tag size="large" type="warning">{{
                t("uknownList.当前有_个包裹待换单").replace(
                  "_",
                  tabs.data[item.key] && tabs.data[item.key].length > 0
                    ? tabs.data[item.key].length
                    : 0
                )
              }}</van-tag>
            </template>
          </van-cell>
          <van-cell :value="t('uknownList.库位编号')" size="large">
            <template #title>
              {{ t("uknownList.包裹编号") }}
            </template>
          </van-cell>
          <van-collapse
            v-if="tabs.data[item.key] && tabs.data[item.key].length > 0"
            v-model="activeNames"
          >
            <!-- icon="orders-o" -->
            <!-- <van-icon name="question-o" /> -->
            <van-collapse-item
              v-for="order in tabs.data[item.key]"
              :key="order.packageNumber"
              :title="order.packageNumber"
              :name="order.packageNumber"
              :value="order.storageBlock"
            >
              <template #title>
                <div>
                  {{ order.packageNumber }}
                  <van-tag class="text-green-500">{{
                    trsansZH2Locale(order.orderReturnClaimStatus)
                  }}</van-tag>
                </div>
              </template>
              <van-cell
                :title="t('uknownList.原始单号')"
                :value="order.packageNumber"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.签入日期')"
                :value="order.checkinDate"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.仓库')"
                :value="order.depot"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.到仓状态')"
                :value="trsansZH2Locale(order.claimCheckInStatus)" 
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领状态')"
                :value="trsansZH2Locale(order.orderReturnClaimStatus)"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.原因')"
                :value="order.reason"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领人')"
                :value="order.advancedClientName"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领人备注')"
                :value="order.advancedMemo"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领日期')"
                :value="order.advancedDate"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领单号')"
                :value="order.advancedWaybillNumber"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领供应商单号')"
                :value="order.advancedProviderNumber"
                size="normal"
              />
              <!-- <van-button type="primary" @click="print(order)" size="small" block>{{
                t("uknownList.打印面单")
              }}</van-button> -->
            </van-collapse-item>
          </van-collapse>
          <van-empty v-else :description="t('noData')" :image="img_index_path" />
        </template>

        <template v-if="item.key == 'ALL'">
          <van-cell>
            <template #title>
              <van-tag size="large" type="warning">{{
                t("uknownList.当前有_个无头件包裹").replace(
                  "_",
                  tabs.data[item.key] && tabs.data[item.key].length > 0
                    ? tabs.data[item.key].length
                    : 0
                )
              }}</van-tag>
            </template>
          </van-cell>
          <van-cell :value="t('uknownList.库位编号')" size="large">
            <template #title>
              {{ t("uknownList.包裹编号") }}
            </template>
          </van-cell>
          <van-collapse
            v-if="tabs.data[item.key] && tabs.data[item.key].length > 0"
            v-model="activeNames"
          >
            <!-- icon="orders-o" -->
            <!-- <van-icon name="question-o" /> -->
            <van-collapse-item
              v-for="order in tabs.data[item.key]"
              :key="order.packageNumber"
              :title="order.packageNumber"
              :name="order.packageNumber"
              :value="order.storageBlock"
            >
              <template #title>
                <div>
                  {{ order.packageNumber }}
                  <van-tag class="text-green-500">{{
                    trsansZH2Locale(order.orderReturnClaimStatus) 
                  }}</van-tag>
                </div>
              </template>
              <van-cell
                :title="t('uknownList.原始单号')"
                :value="order.packageNumber"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.签入日期')"
                :value="order.checkinDate"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.仓库')"
                :value="order.depot"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.到仓状态')"
                :value="trsansZH2Locale(order.claimCheckInStatus)"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领状态')"
                :value="trsansZH2Locale(order.orderReturnClaimStatus)"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.原因')"
                :value="order.reason"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领人')"
                :value="order.advancedClientName"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领人备注')"
                :value="order.advancedMemo"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领日期')"
                :value="order.advancedDate"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领单号')"
                :value="order.advancedWaybillNumber"
                size="normal"
              />
              <van-cell
                :title="t('uknownList.认领供应商单号')"
                :value="order.advancedProviderNumber"
                size="normal"
              />
              <!-- <van-button type="primary" @click="print(order)" size="small" block>{{
                t("uknownList.打印面单")
              }}</van-button> -->
            </van-collapse-item>
          </van-collapse>
          <van-empty v-else :description="t('noData')" :image="img_index_path" />
        </template>
      </van-tab>
      <!-- </van-list> -->
    </van-pull-refresh>
    <!-- </template> -->
  </van-tabs>
</template>

<script setup lang="ts">
import img_index_path from "~/noData.png";
// import router from "@/router";
// import { useStore } from "@/stores";
// import { localStorage } from "@/utils/local-storage";
import { postRequest } from "@/api";
import { AppToast } from "@/utils/appToast";
import { useI18n } from "vue-i18n";
import { DEPOT_CODE } from "@/utils/constant";
const { t } = useI18n();
// const store = useStore();
const active = ref(0);

// PHOTO Begin
const scan = ref("");
const unknowOrder = ref({});
const fileList = ref([]);
const tipState = reactive({
  color: "white",
  background: "white",
  info: "",
  infoClass: "",
});
const trsansZH2Locale = (msg) =>{
  switch (msg) {
    case "已到仓":
      return t("trsansZH2Locale.已到仓");
    case "未到仓":
      return t("trsansZH2Locale.未到仓");
    case "已认领":
      return t("trsansZH2Locale.已认领");
    default:
      return t("trsansZH2Locale.default");
  }
}

const handleScan = () => {
  if(scan.value == ""){
    AppToast(t("uknownList.请输入包裹编号"),'danger',true);
    return;
  }
  tipState.info = ""; 
  unknowOrder.value = ref({});
  fileList.value.length = 0;

  postRequest("/ReturnOrderService/claim/query", {
    depot: DEPOT_CODE,
    packageNumber: scan.value,
    offset: 0,
    limit: 200,
    returnClaimed: false,
    waitForPrint: false,
  }).then((res) => {
    if (res.status === 200) {
      if (res.data.length > 0) {
        unknowOrder.value = res.data[0];
        // unknowOrder.value['images'] = [
        //   'https://fastly.jsdelivr.net/npm/@vant/assets/sand.jpeg'
        // ]
        JSON.parse(unknowOrder.value['images']).forEach((item) => {
          fileList.value.push({
            url: item,
            deletable: false,
          });
        }); 
        console.log(fileList.value)
        console.log(unknowOrder.value)
        tipState.info = t("uknownList.扫描成功");
        tipState.background = "green";
      } else {
        tipState.info = t("uknownList.无此无头件");
        tipState.background = "red";
      }
    } else { 
      tipState.info = t("uknownList.扫描失败");
      tipState.background = "red";
    }
  });
};

const afterRead = (file) => {
  const formData = new FormData();
  formData.append("file", file.file);

  file.status = "uploading";
  file.message = t('uploading') ;
  postRequest("/ReturnOrderService/claim/uploadImage", formData)
    .then((response) => {
      if (response.status === 200) {
        file.url = response.data;
        file.status = "done";
        file.message = t("uknownList.上传成功");
      } else {
        file.status = "failed";
        file.message = t("uknownList.上传失败");
        AppToast(response.message, "fail");
      }
    })
    .catch(() => {
      file.status = "failed";
      file.message = t("uknownList.上传失败");
    });
};

const handleHeadlessFormSubmit = () => {
  if (fileList.value.length === 0) {
    AppToast(t("uknownList.请上传图片"), "fail");
    return;
  }
  if (unknowOrder.value['packageNumber']=== undefined) {
    AppToast(t("uknownList.请扫描无头件单号"), "fail");
    return;
  }
  const images = [];
  fileList.value.forEach((item) => {
    images.push(item.url);
  });
  postRequest("/ReturnOrderService/claim/update", {
    id: unknowOrder.value['id'], 
    images: images,
  }).then((res) => {
    if (res.status === 200) {
      AppToast(t("uknownList.保存成功"), "success");
      scan.value = "";
      unknowOrder.value = {};
      fileList.value.length = 0;
    } else {
      AppToast(res.message, "fail");
    }
  }); 
};

// PHOTO End
const loadingRefresh = ref(false);

const activeNames = ref(["0"]);
const tabs = reactive({
  tabName: [
    {
      index: 0,
      title: t("uknownList.无头件拍照"),
      key: "PHOTO",
    },
    {
      index: 1,
      title: t("uknownList.待换单"),
      key: "TOHANDLE",
      loadData: true,
    },
    {
      index: 2,
      title: t("uknownList.全部"),
      key: "ALL",
      loadData: true,
    },
  ],
  data: {},
  offset: {},
  page: {},
});

const loadToHandle = async (tabType) => {
  if (tabType == "TOHANDLE") {
    postRequest("/ReturnOrderService/claim/query", {
      depot: DEPOT_CODE,
      offset: 0,
      limit: 200, 
      waitForPrint: true,
    }).then((res) => {
      if (res.status === 200) {
        console.log(res.data);
        tabs.data[tabType] = res.data;
        // tabs.offset[tabType] = 100;
        // tabs.page[tabType] = 1;
        AppToast(t("uknownList.刷新成功"));
      } else {
        // AppToast(res.message, "fail");
      }
    });
  }
  if (tabType == "ALL") {
    postRequest("/ReturnOrderService/claim/query", {
      depot: DEPOT_CODE,
      offset: 0,
      limit: 200,
      returnClaimed: false,
      waitForPrint: false,
    }).then((res) => {
      if (res.status === 200) {
        console.log(res.data);
        tabs.data[tabType] = res.data;
        // tabs.offset[tabType] = 100;
        // tabs.page[tabType] = 1;
        AppToast(t("uknownList.刷新成功"));
      } else {
        // AppToast(res.message, "fail");
      }
    });
  }
};

// list
// const loading = ref(false);
// const finished = ref(false);
// //数据加载
// const listOnLoad = () => {};

const onRefresh = () => {
  const tabType = tabs.tabName.filter((item) => item.index === active.value)[0];
  console.log("tabType", tabType);
  if (tabType.loadData === true) {
    loadToHandle(tabType.key);
  }
  setTimeout(() => {
    loadingRefresh.value = false;
  }, 500);
};
const init = async () => {
  for (let i = 0; i < tabs.tabName.length; i++) {
    const tabType = tabs.tabName[i].key;
    await loadToHandle(tabType);
  }
};
init();
const onClickLeft = () => history.back();
// const print = (order) => {
//   console.log(order);
// };
</script>

<style lang="less" scoped></style>
